﻿using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonServiceLocator;
using Microsoft.WindowsAPICodePack.Dialogs;
using System.IO;

namespace GenCapacitorTypes.ViewModels
{
    class MainViewModel
    {
        public RelayCommand CommandDoAnalyse => new RelayCommand(() =>
        {

            var dialog = new CommonOpenFileDialog();
            dialog.IsFolderPicker = true;
            CommonFileDialogResult result = dialog.ShowDialog();
            Status = "分析中...";
            if (result == CommonFileDialogResult.Ok)
            {
                string folderPath = dialog.FileName;

                List<Models.AnalyseResult> analyseResults = new List<Models.AnalyseResult>();

                List<string> filesNotDone = new List<string>();
               

                string[] files = Directory.GetFiles(folderPath, "*.doc*");
                foreach (string file1 in files)
                {
                    try
                    {
                        //转换为因为括号
                        string file = Path.GetFileName(file1);
                        file = file.Replace("（", "(");//
                        file = file.Replace("）", ")");

                        //找到左括号
                        int pos1 = file.IndexOf("(");
                        int pos2 = file.LastIndexOf(")");

                        //

                        string got = file.Substring(pos1 + 1, pos2 - pos1 - 1);
                        //删除空格
                        got = got.Replace(" ", "");
                        char[] codes = got.ToCharArray();

                        int lastChinese = 0;
                        for (int i = codes.Length - 1; i > 0; i--)
                        {
                            if (codes[i] >= 0x4e00)
                            {
                                lastChinese = i;
                                break;
                            }
                        }

                        string customer = got.Substring(0, lastChinese + 1);
                        string type = got.Substring(lastChinese + 1);

                        if (string.IsNullOrEmpty(customer) || string.IsNullOrEmpty(type))
                        {
                            throw new Exception();
                        }

                        try
                        {
                            var found=analyseResults.Where(a => a.Customer == customer && a.Type == type).First();
                        }
                        catch(Exception exinner)
                        {
                            analyseResults.Add(new Models.AnalyseResult()
                            {
                                Customer = customer,
                                Type = type,
                                FileName=file1
                            }) ;
                        }                    


                    }
                    catch (Exception ex)
                    {
                        filesNotDone.Add(file1);
                    }



                }

                Status = "分析完成";
                //写入文件
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                string DataFilePath = "e:\\temp\\客户-型号.xlsx";
                using (var package = new OfficeOpenXml.ExcelPackage(new FileInfo(DataFilePath)))
                {
                    //先删除表
                    try
                    {
                        package.Workbook.Worksheets.Delete("customer-type");
                        package.Workbook.Worksheets.Delete("error");
                    }
                    catch
                    {
                        //没有该表会发生异常，忽略
                    }
                    //

                    //增加表
                    var sheet1 = package.Workbook.Worksheets.Add("customer-type");
                    var sheet2 = package.Workbook.Worksheets.Add("error");
                    string[] headers = new string[]
                    {
                        "客户",
                        "型号",
                        "文件名"

                    };
                    for (int i = 0; i < headers.Length; i++)
                    {
                        sheet1.Cells[1, i + 1].Value = headers[i];
                    }

                    sheet2.Cells[1, 1].Value = "文件名";

                    //列格式


                    //写入数据
                    int rowIndex = 1;

                    for (int i = 0; i < analyseResults.Count; i++)
                    {
                        rowIndex++;
                        sheet1.Cells[rowIndex, 1].Value = analyseResults[i].Customer;
                        sheet1.Cells[rowIndex, 2].Value = analyseResults[i].Type;
                        sheet1.Cells[rowIndex, 3].Value = analyseResults[i].FileName;
                    }
                    //
                    rowIndex = 1;
                    for (int i = 0; i < filesNotDone.Count; i++)
                    {
                        rowIndex++;
                        sheet2.Cells[rowIndex, 1].Value = filesNotDone[i];                        
                    }




                    package.Save();


                }

                Status = $"已写入文件{DataFilePath}";


            }
        });

        public RelayCommand CommandDoAnalyse1 => new RelayCommand(() =>
        {

            var dialog = new CommonOpenFileDialog();
            //dialog.IsFolderPicker = true;
            CommonFileDialogResult result = dialog.ShowDialog();
            Status = "分析中...";
            if (result == CommonFileDialogResult.Ok)
            {
                string path = dialog.FileName;

                

               


            }
        });
        public string Status { get; set; } = "===========";
    }
}
